package com.hwatsang.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hwatsang.remote.rest.HttpAccessHelper;
import com.hwatsang.service.SmsService;

public class DoutwoSmsServiceImpl implements SmsService {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(DoutwoSmsServiceImpl.class);
	
	private String smsUser;
	private String smsPassword;
	private String smsApiUrl;
	
	public void sendSms(String mobileNumber, String content) {
		
		LOGGER.info("Sending sms [{}] to number [{}].", content, mobileNumber);
		
		StringBuilder sb = new StringBuilder(smsApiUrl);
		try {
			sb.append("/smsSender/")
				.append(smsUser).append("/")
				.append(smsPassword).append("/")
				.append(URLEncoder.encode(content, "utf-8")).append("/")
				.append(mobileNumber);
		} catch (UnsupportedEncodingException e1) {}
		
		String jsonResult = null;
		try {
			jsonResult = HttpAccessHelper.executeGetWithoutParam(sb.toString());
		} catch (IOException e) {
			LOGGER.error(e.getMessage(), e);
		}
		
		LOGGER.info("Sms has sent and sms server return result {}.", jsonResult);
	}
	
	public int checkBalance() {
		
		StringBuilder sb = new StringBuilder(smsApiUrl);
		sb.append("/remainCount/")
			.append(smsUser).append("/")
			.append(smsPassword).append("/");
		
		String result = null;
		try {
			result = HttpAccessHelper.executeGetWithoutParam(sb.toString());
		} catch (IOException e) {
			LOGGER.error(e.getMessage(), e);
		}
		
		return Integer.valueOf(result);
	}
	
	public List<String> checkSendHistory() {
		throw new RuntimeException("Not yet implemented!");
//		StringBuilder sb = new StringBuilder(smsApiUrl);
//		try {
//			sb.append("/smsSendList/")
//				.append(smsUser).append("/")
//				.append(smsPassword).append("/")
//				.append("1").append("/")
//				.append(URLEncoder.encode("2012-08-23 21:00:00", "utf-8")).append("/")
//				.append(URLEncoder.encode("2021-08-23 00:00:00", "utf-8"));
//		} catch (UnsupportedEncodingException e1) {/*never gonna happen*/}
//		
//		String result = null;
//		try {
//			result = HttpAccessHelper.executeGetWithoutParam(sb.toString());
//		} catch (IOException e) {
//			LOGGER.error(e.getMessage(), e);
//		}
//				
//		return null;
	}

	public void setSmsUser(String smsUser) {
		this.smsUser = smsUser;
	}

	public void setSmsPassword(String smsPassword) {
		this.smsPassword = smsPassword;
	}

	public void setSmsApiUrl(String smsApiUrl) {
		this.smsApiUrl = smsApiUrl;
	}
}
